package com.tarena.lbs.stock.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.pojo.stock.param.CouponStockParam;
import com.tarena.lbs.pojo.stock.po.CouponStockPO;
import com.tarena.lbs.stock.web.repository.StockRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class StockService {
    @Autowired
    private StockRepository stockRepository;

    public boolean initCouponStock(CouponStockParam param) {
        //组织一个po 新增save根据save方法返回值 rows 判断数据库是否真的成功
        CouponStockPO po=new CouponStockPO();
        po.setBusinessId(param.getBusinessId());
        po.setCouponId(param.getCouponId());
        po.setNum(param.getNum());
        po.setCreateAt(new Date());
        po.setUpdateAt(new Date());
        //新增一条 调用新增
        return stockRepository.save(po);
    }

    public Integer getCouponStock(Integer couponId) {
        //select * from coupon_stock where coupon_id=?
        QueryWrapper<CouponStockPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("coupon_id",couponId);
        CouponStockPO one = stockRepository.getOne(queryWrapper);
        if (one!=null){
            return one.getNum();
        }
        return null;
    }

    public boolean reduceCouponStock(Integer couponId, Integer num) {
        //update coupon_stock set num=num-1,update_at=now() where coupon_id=? and num>=?
        return stockRepository.updateCouponStock(couponId,num);
    }
}
